/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.saashousekeeper.config;

import com.huawei.saashousekeeper.constants.CommonConstants;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 保存当前租户标识
 *
 * @since 2022-02-14
 */
public class TenantContext {
    private static final HystrixRequestVariableDefault<Map<String, String>> TENANT_KEY =
            new HystrixRequestVariableDefault<>();

    public static String getDomain() {
        return Optional.ofNullable(TENANT_KEY.get()).orElse(new HashMap<>()).get(CommonConstants.TENANT_DOMAIN);
    }

    /**
     * 初始化时设置domain，直到会话结束时才会销毁
     *
     * @param domain 标识
     */
    public static void setDomain(String domain) {
        HystrixRequestContext.initializeContext();
        Map<String, String> variableMap = new HashMap<>(2);
        variableMap.put(CommonConstants.TENANT_DOMAIN, domain);

        // 默认主库
        variableMap.put(CommonConstants.DB_STRATEGY, CommonConstants.DB_SLAVE);
        TENANT_KEY.set(variableMap);
    }

    /**
     * 在有租户的前提下，携带数据操作类型
     *
     * @param sqlCommandType 操作类型
     */
    public static void setDbStrategyType(String sqlCommandType) {
        if (CommonConstants.DB_SLAVE.equalsIgnoreCase(sqlCommandType)) {
            return;
        }
        Optional.ofNullable(TENANT_KEY.get())
                .ifPresent(map -> map.put(CommonConstants.DB_STRATEGY, CommonConstants.DB_MASTER));
    }

    /**
     * 获取当前会话的主从策略
     *
     * @return 策略
     */
    public static String getDbStrategyType() {
        return Optional.ofNullable(TENANT_KEY.get()).orElse(new HashMap<>()).get(CommonConstants.DB_STRATEGY);
    }

    public static void remove() {
        TENANT_KEY.remove();
    }
}
